//
//  TabbarController.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/4.
//

import UIKit

// 是否中间按钮凸起
let setCustomBar : Bool = false

class TabbarController : QMUITabBarViewController {
    
    lazy var homeNav : QMUINavigationController = {
        let vc = HomeViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "首页", image: UIImage(named: "icon_home_off1")?.withRenderingMode(.alwaysOriginal), tag: 0)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on1")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()

    lazy var homeNav2 : QMUINavigationController = {
        let vc = FQHomeViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "首页", image: UIImage(named: "icon_home_off1")?.withRenderingMode(.alwaysOriginal), tag: 0)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on1")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()
    
    lazy var investigationNav : QMUINavigationController = {
        let vc = FQInvestigationViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "贷前必查", image: UIImage(named: "icon_home_off2")?.withRenderingMode(.alwaysOriginal), tag: 1)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on2")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()
    
    lazy var memberNav : QMUINavigationController = {
        let vc = FQMemberViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "会员", image: UIImage(named: "icon_home_off3")?.withRenderingMode(.alwaysOriginal), tag: 2)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on3")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()
    
    lazy var organizationNav : QMUINavigationController = {
        let vc = FQOrganizationViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "合作机构", image: UIImage(named: "icon_home_off4")?.withRenderingMode(.alwaysOriginal), tag: 3)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on4")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()
    
    lazy var mineNav : QMUINavigationController = {
        let vc = MineViewController()
        vc.hidesBottomBarWhenPushed = false
        let nav = QMUINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(title: "我的", image: UIImage(named: "icon_home_off5")?.withRenderingMode(.alwaysOriginal), tag: 4)
        nav.tabBarItem.selectedImage = UIImage(named: "icon_home_on5")?.withRenderingMode(.alwaysOriginal)
        return nav
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 读取plist文件
//        let tabBarFilePath : URL = Bundle.main.url(forResource: "tabBar", withExtension: "plist")!
//        let tabBarData : Data = try! Data(contentsOf: tabBarFilePath)
//        let dict : [String : [String]] = try! PropertyListSerialization.propertyList(from: tabBarData, options: [], format: nil) as! [String : [String]]
        
        var viewControllerArray : [QMUINavigationController] = [homeNav, mineNav]
        if let model = BaseUserModel.unarchiver(), model.isAccomplishWorkInfo, model.isAccomplishRelationship, model.isAccomplishLoanInfo {
            viewControllerArray = [homeNav2, mineNav]
        }
        if setCustomBar {
            let tabBar = TabBar(frame: CGRect.init(x: 0, y: view.bounds.height - TabBarHeight, width: view.bounds.width, height: TabBarHeight))
            setValue(tabBar, forKey: "tabBar")
            
//            tabBar.buttonClickBlock = { [unowned self] in
//                self.selectedIndex = titleArray.count / 2 + 1
//            }
        }
        // 由于tabbarcontroller代码手动调整selectedIndex无法响应shouldSelect代理方法，所以替换selectedIndex方法使之响应shouldSelect
        Self.swizzleMethod(for: Self.self, originalSelector: #selector(setter: selectedIndex), swizzledSelector: #selector(setSelected(index:)))

        self.delegate = self
//        for (index,value) in viewControllerArray.enumerated() {
//            let nav = value
//            if viewControllerArray.count / 2 == index && setCustomBar {
//                nav.tabBarItem.imageInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: -15, right: 0)
//            }
//        }
        viewControllers = viewControllerArray
        
        CustomRelay.manager.tabbarStatusBehaviorRelay.subscribe (onNext:{ [weak self] status in
            guard let self = self else { return }
//            UIView.transition(with: view, duration: 0.5, options: .transitionFlipFromTop) {
                if status {
                    viewControllerArray = [self.homeNav2, self.mineNav]
    //                viewControllerArray = [self.homeNav, self.investigationNav, self.memberNav, self.organizationNav, self.mineNav]
                    self.setViewControllers(viewControllerArray, animated: true)
                } else {
                    viewControllerArray = [self.homeNav, self.mineNav]
                    self.setViewControllers(viewControllerArray, animated: true)
                }
//            }
        }).disposed(by: rx.disposeBag)
    }
}

extension TabbarController : UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        DeviceManager.doImpactFeedback()
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//        let nav : QMUINavigationController = viewController as! QMUINavigationController
//        let vc : UIViewController = nav.viewControllers.first!
//        if (vc.self == vc.self && tabBarController.selectedIndex == 0) {
//            // 监听首页的重复点击
//            NotificationCenter.default.post(name: NSNotification.Name("TabbarButtonClickDidRepeatNotification"), object: nil);
//        }
        return true
    }
    
    @objc func setSelected(index : Int) {
        if index >= children.count || index < 0 { return }
        if delegate == nil {
            willChangeValue(forKey: "selectedViewController")
            selectedIndex = index
            didChangeValue(forKey: "selectedViewController")
        } else {
            let willBeSelectController = children[index]
            if canSelectController(willBeSelectController: willBeSelectController) {
                willChangeValue(forKey: "selectedViewController")
                setSelected(index: index)
                if delegate != nil && (delegate?.responds(to: #selector(tabBarController(_:didSelect:))))! {
                    delegate?.responds(to: #selector(tabBarController(_:didSelect:)))
                }
                didChangeValue(forKey: "selectedViewController")
            }
        }
    }
    
    func canSelectController(willBeSelectController : UIViewController) -> Bool {
        if delegate != nil && delegate!.responds(to: #selector(tabBarController(_:shouldSelect:))) {
            return delegate!.responds(to: #selector(tabBarController(_:shouldSelect:)))
        } else {
            return true
        }
    }
}
